from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import GenericViewSet

from users import serializers

from users.serializers import UserInfoSerializer

from goods.models import SKU
from .models import User


class CheckUsernameView(APIView):
    def get(self, request, username):
        # 1,根据用户名查询,用户数量
        count = User.objects.filter(username=username).count()

        # 2,返回响应
        data = {
            "count": count
        }
        return Response(data, status=status.HTTP_200_OK)


class CheckMobileView(APIView):
    def get(self, request, mobile):
        # 1,根据手机号查询,用户数量
        count = User.objects.filter(mobile=mobile).count()

        # 2,返回响应
        data = {
            "count": count
        }
        return Response(data, status=status.HTTP_200_OK)


class RegisterUserView(CreateAPIView):
    serializer_class = serializers.RegisterUserSerializer

    # def post(self,request):
    # 一, 只继承自了GenericAPIView
    # #1,获取参数
    # dict_data = request.data
    #
    # #2,创建序列化器,校验
    # serializer =  self.get_serializer(data=dict_data)
    # serializer.is_valid(raise_exception=True)
    #
    # #3,数据入库
    # serializer.save()
    #
    # #4,返回响应
    # return Response(serializer.data,status=status.HTTP_201_CREATED)

    # 二,使用了mixin + GenericAPIView
    # return self.create(request)

class UserInfoView(RetrieveAPIView):
    serializer_class = UserInfoSerializer
    permission_classes = [IsAuthenticated]  # 认证的用户

    def get_object(self):
        return self.request.user

class EmailSendView(UpdateAPIView):
    serializer_class = serializers.EmailSendSerializer
    permission_classes = [IsAuthenticated]
    def get_object(self):
        return self.request.user


class EmailActiveView(APIView):
    def get(self, request):
        # 1,获取参数token
        token = request.query_params.get("token")

        # 2,为空校验
        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 3,解密token
        user = User.decode_token(token)
        if not user:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 4,数据入库(修改email_active属性)
        user.email_active = True
        user.save()

        # 5,返回响应
        return Response(status=status.HTTP_200_OK)

class AddressView(mixins.UpdateModelMixin,
                  mixins.CreateModelMixin,
                  GenericViewSet):
    serializer_class = serializers.AddressSerializer

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request):
        # 1,获取用户地址信息
        queryset = self.get_queryset()

        # 2,获取序列化器
        serializer = self.get_serializer(instance=queryset, many=True)

        # 3,返回
        return Response({
            "addresses": serializer.data,
            "limit": 20,
            "default_address_id": request.user.default_address_id
        })

    # 1,重写地址创建方法,判断用户的地址是否已经达到20个了
    def create(self, request, *args, **kwargs):
        # #1,获取参数
        # dict_data = request.data
        #
        # #2,获取序列化器
        # serializer = self.get_serializer(data=dict_data)
        #
        # #3,校验入库
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        #
        # #4,返回
        # return Response(serializer.data)

        # 1,获取用户地址数量
        count = request.user.addresses.filter(is_deleted=False).count()

        # 2,判断地址的数量
        if count >= 20:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 3,调用父类方法即可
        return super(AddressView, self).create(request, *args, **kwargs)


    @action(methods=['put'],detail=True) #格式: addresses/pk/status
    def status(self,request,pk):
        request.user.default_address_id = pk
        request.user.save()
        return Response(status=status.HTTP_200_OK)

class UserBrowerHistoryView(CreateAPIView):
    serializer_class = serializers.UserBrowerHistorySerializer

    # def post(self,request):
    #
    #     #1,获取参数
    #     dict_data = request.data
    #
    #     #2,获取序列化器,校验
    #     serializer = self.get_serializer(data=dict_data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     #3,入库(保存到redis中)
    #     serializer.save()
    #
    #     #4,返回
    #     return Response(serializer.data)
    def get(self, request):
        # 1,获取redis中的数据
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s" % request.user.id, 0, 4)

        # 2,拼接数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "default_image_url": sku.default_image_url,
                "name": sku.name,
                "price": sku.price,
                "comments": sku.comments,
                "id": sku.id
            }
            sku_list.append(sku_dict)

        # 3,返回
        return Response(sku_list)